package data.crawling;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

@Deprecated
public class TermBuilder extends Builder{
	String output_filename;
	
	public TermBuilder(String name){
		super();
		this.output_filename = name;
	}
	
	public void buildTerms(ArrayList<String> terms){
		//only consider two levels down from Glossary
		HashMap<String, HashSet<String>> tax = new HashMap<String, HashSet<String>>();
		for(String s:terms){
			String[] ts = s.split(":");
			if(ts.length<2){
				continue;
			}
			int j=-1;
			for(int i =0; i<ts.length; i++){
				if(ts[i].trim().equals(Builder.GLOSSARY)){
					//start getting termsnow
					j=i;
					break;
				}
			}
			if(j >= 0){		
				for(; j<ts.length-1; j++){
					this.addItem(tax, ts[j+1], ts[j]);
				}
			}
		}
		//write the taxonomy in our syntax and serialize it.
		this.writeTax(tax, this.output_filename);
		return;
	}
	
	
	private void writeTax(HashMap<String, HashSet<String>> tax, String filename){
		FileWriter fstream = null;
		BufferedWriter out = null;
		try{
		    fstream = new FileWriter(filename + ".tbox", true);
	        out = new BufferedWriter(fstream);
	        for(String s:tax.keySet()){
	        	boolean single = tax.get(s).size()>1;
	        	String ws = "(implies "+s+" ";
	        	if(single)	ws +=  " (and ";
	        	for(String ss : tax.get(s)){
	        		ws += ss+" ";
	        	}
	        	if(single) ws+= ")"; 
	        	ws += ")";
	        	out.append(ws);
	        	out.newLine();
	        }

		}catch(Exception e){
			e.printStackTrace();
		} finally {
			try {
				fstream.close();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    
		}
	}
	
	private void addItem(HashMap<String, HashSet<String>> tax, String sub, String sup){
		sub = KBBuilder.normalizeString( Builder.stringToConcept(sub));
		sup = KBBuilder.normalizeString(Builder.stringToConcept(sup));
		HashSet<String> sups = null;
		if(tax.containsKey(sub)){
			if(!tax.get(sub).contains(sup)){
				sups = tax.get(sub);
				sups.add(sup);
				tax.put(sub, sups);	
			}
		}else{
			sups = new HashSet<String>();
			sups.add(sup);
			tax.put(sub, sups);	
		}
		//System.out.println("added: "+sub+" -> "+sup);
	}
	
	
	
}
